package com.team.RunsFast_Api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.RunsFast_Api.dao.AddressDao;
import com.team.RunsFast_Api.dto.AddressDetailDto;
import com.team.RunsFast_Api.service.intf.AddressService;
import com.team.runsfast.entity.Address;
import com.team.runsfast.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    private final AddressDao addressDao;

    public AddressServiceImpl(AddressDao addressDao) {
        this.addressDao = addressDao;
    }

    @Override
    public R save(Address obj, String token) {
        //判断传过来数据的有效性
        if (obj!=null) {
            //获得用户id
            Long uid = Long.parseLong(token);
            obj.setUid(uid);
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",uid);
            queryWrapper.eq("name",obj.getName());
            queryWrapper.eq("phone",obj.getPhone());
            queryWrapper.eq("city",obj.getCity());
            queryWrapper.eq("country",obj.getCountry());
            queryWrapper.eq("address",obj.getAddress());
            if (addressDao.selectOne(queryWrapper)!=null) {
                return R.fail("地址已存在，添加失败");
            }else {
                if (addressDao.insert(obj) > 0) {
                    if (obj.getFlag() == 1) {
                        addressDao.updateFlag(obj.getId());
                    }
                    return R.ok("添加成功");
                } else {
                    return R.fail("添加失败");
                }
            }
        }
        return R.fail("添加失败");
  }

    @Override
    public R queryAll() {
        return R.ok(addressDao.selectList(null));
    }

    @Override
    public R del(long id) {
        if (addressDao.deleteById(id)>0) {
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R queryMy(String token) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",Long.parseLong(token));
        queryWrapper.orderByAsc("id");
        List<Address> list = addressDao.selectList(queryWrapper);
        List<AddressDetailDto> dtos = new ArrayList<>();

        list.forEach(a->{
            AddressDetailDto dto = new AddressDetailDto();
            BeanUtils.copyProperties(a,dto);

            if (a.getFlag()==1){
                addressDao.updateFlag(a.getId());
            }

            dto.setDetail(a.getAddress());
            dto.setAddress(a.getCity()+"市"+a.getCountry()+"县"+a.getAddress());
            dto.setTel(a.getPhone());
            dtos.add(dto);
        });
        return R.ok(dtos);
    }
}
